package com.lewis.system.controller;


import com.lewis.core.annotation.Log;
import com.lewis.core.base.controller.BaseController;
import com.lewis.core.base.domain.BaseResult;
import com.lewis.core.base.domain.entity.SysUser;
import com.lewis.core.base.domain.model.LoginUser;
import com.lewis.core.config.LewisConfig;
import com.lewis.core.constant.UserConstants;
import com.lewis.core.enums.BusinessType;
import com.lewis.core.utils.MapUtil;
import com.lewis.core.utils.SecurityUtil;
import com.lewis.core.utils.ServletUtil;
import com.lewis.core.utils.StringUtil;
import com.lewis.core.utils.file.FileUploadUtil;
import com.lewis.system.service.ISysUserService;
import com.lewis.system.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * 个人信息 业务处理
 *
 * @author Lewis
 */
@Api(tags = "个人信息 业务处理")
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {

	@Resource
	private ISysUserService userService;

	@Resource
	private TokenService tokenService;

	@ApiOperation(value = "个人信息", notes = "个人信息")
	@GetMapping
	public Object profile() {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtil.getRequest());
		SysUser user = loginUser.getUser();
		BaseResult ok = ok().setData(user);
		Map<String, Object> resultMap = MapUtil.object2MapByReflect(ok);
		return resultMap;
	}

	@ApiOperation(value = "修改用户", notes = "修改用户")
	@Log(title = "个人信息", businessType = BusinessType.UPDATE)
	@PutMapping
	public BaseResult updateProfile(@RequestBody SysUser user) {
		if (StringUtil.isNotEmpty(user.getPhoneNumber())
				&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {

			return fail().setMsg("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
		}

		if (StringUtil.isNotEmpty(user.getEmail())
				&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {

			return fail().setMsg("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}

		LoginUser loginUser = tokenService.getLoginUser(ServletUtil.getRequest());
		SysUser sysUser = loginUser.getUser();
		user.setId(sysUser.getId());
		user.setPassword(null);
		if (userService.updateUserProfile(user) > 0) {
			// 更新缓存用户信息
			loginUser.getUser().setNickName(user.getNickName());
			loginUser.getUser().setPhoneNumber(user.getPhoneNumber());
			loginUser.getUser().setEmail(user.getEmail());
			loginUser.getUser().setSex(user.getSex());
			tokenService.setLoginUser(loginUser);
			return ok();
		}
		return fail().setMsg("修改个人信息异常，请联系管理员");
	}

	@ApiOperation(value = "重置密码", notes = "重置密码")
	@Log(title = "个人信息", businessType = BusinessType.UPDATE)
	@PutMapping("/updatePwd")
	public BaseResult updatePwd(String oldPassword, String newPassword) {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtil.getRequest());
		String userName = loginUser.getUsername();
		String password = loginUser.getPassword();
		if (!SecurityUtil.matchesPassword(oldPassword, password)) {
			return fail().setMsg("修改密码失败，旧密码错误");
		}
		if (SecurityUtil.matchesPassword(newPassword, password)) {
			return fail().setMsg("新密码不能与旧密码相同");
		}
		if (userService.resetUserPwd(userName, SecurityUtil.encryptPassword(newPassword)) > 0) {
			// 更新缓存用户密码
			loginUser.getUser().setPassword(SecurityUtil.encryptPassword(newPassword));
			tokenService.setLoginUser(loginUser);
			return ok();
		}
		return fail().setMsg("修改密码异常，请联系管理员");
	}

	@ApiOperation(value = "头像上传", notes = "头像上传")
	@Log(title = "用户头像", businessType = BusinessType.UPDATE)
	@PostMapping("/avatar")
	public Object avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
		if (!file.isEmpty()) {
			LoginUser loginUser = tokenService.getLoginUser(ServletUtil.getRequest());
			String avatar = FileUploadUtil.upload(LewisConfig.getAvatarPath(), file);
			if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
				BaseResult ok = ok();
				Map<String, Object> ajax = MapUtil.object2MapByReflect(ok);
				ajax.put("imgUrl", avatar);
				// 更新缓存用户头像
				loginUser.getUser().setAvatar(avatar);
				tokenService.setLoginUser(loginUser);
				return ajax;
			}
		}
		return fail().setMsg("上传图片异常，请联系管理员");
	}
}
